import { Injectable } from '@angular/core';


declare var window: any;

@Injectable()
export class IndexedDBService {

    myId: string;
    db: any;
    userInfors = {};

    communications: any[] = [
        {COMMU_USER_ID: '10000001', TYPE: 'U', LATEST_USER_ID: '10000000', CONTENT: '你好', UPDATE_TIME: '2017-08-13 14:21:39', IS_TOP: 0, NO_READ_MSG: 2},
        {COMMU_USER_ID: '10000002', TYPE: 'U', LATEST_USER_ID: '10000000', CONTENT: '你是谁', UPDATE_TIME: '2017-08-10 13:31:39', IS_TOP: 0, NO_READ_MSG: 10},
        {COMMU_USER_ID: '10000003', TYPE: 'U', LATEST_USER_ID: '10000003', CONTENT: '我管你是谁,是谁是谁谁谁谁......', UPDATE_TIME: '2017-08-03 01:09:03', IS_TOP: 0, NO_READ_MSG: 1}
    ];
    users: any[] = [
        {USER_ID: '10000000', HEAD_PATH: '../assets/img/ben.png', USER_NAME: 'Master'},
        {USER_ID: '10000001', HEAD_PATH: '../assets/img/li.jpg', USER_NAME: '李雷'},
        {USER_ID: '10000002', HEAD_PATH: '../assets/img/han.jpg', USER_NAME: 'han'},
        {USER_ID: '10000003', HEAD_PATH: '../assets/img/mike.png', USER_NAME: '吉姆'}
    ];

    U10000001: any[] = [
        {USER_ID: '10000000', TYPE: 'message', CONTENT: "这行文字足够长足够长足够长足够长足够长足够长足够长足够长可以折行", TIME: '2017-08-13 14:21:39'},
        {USER_ID: '10000001', TYPE: 'message', CONTENT: "Helo 001", TIME: '2017-08-13 14:22:39'},
        {USER_ID: '10000001', TYPE: 'message', CONTENT: "那行文字足够长足够长足够长足够长足够长足够长足够长足够长可以折行", TIME: '2017-08-13 14:22:50'},
    ];

    open(): void {
        let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
        console.log("OK");
            if(indexedDB) {
        } else {
            console.log("NG");
        }
        
        let self = this;
        let request = indexedDB.open("wechat", 1);
        request.onsuccess = function(event) {
            console.log("IndexedDBService onsuccess");
            self.db = request.result;

            self.getAllDate("users")
            .then((result:any) => {
                self.prepareUserInfo(result, self.userInfors);
            })
        };
        request.onerror = this.error;
        request.onupgradeneeded = this.upgradeneeded.bind(this);
    }

    error(event): void {
        console.log("IndexedDBService onerror");
        console.log(event);
    }

    upgradeneeded(event): void {
        console.log("IndexedDBService onupgradeneeded");
        // console.log(event);

        let db = event.target.result;

        if(event.oldVersion == 0) {
            if(!db.objectStoreNames.contains('communications')) {
                let store = db.createObjectStore('communications', {keyPath: "COMMU_USER_ID"});
                
                this.communications.forEach((communication)=>{
                    store.put(communication);
                });
            }

            if(!db.objectStoreNames.contains('users')) {
                let store = db.createObjectStore('users', {keyPath: "USER_ID"});

                this.users.forEach((user)=>{
                    store.put(user);
                });
            }

            if(!db.objectStoreNames.contains('U10000001')) {
                let store = db.createObjectStore("U10000001", { autoIncrement: true });

                this.U10000001.forEach((data)=>{
                    store.put(data);
                });
            }
        }

        this.prepareUserInfo(this.users, this.userInfors);
    }

    private prepareUserInfo(userInfors: any, userInfoDict: any): void {
        userInfors.forEach((element) => {
            let userId = element.USER_ID;
            userInfoDict[userId] = element;
        });

        console.log(userInfoDict);
    }

    getAllDate<T>(table_name:string): Promise<T> {
        return new Promise((resolve, reject) => {
            let store = this.db.transaction(table_name,"readwrite").objectStore(table_name);
            let request = store.getAll();
            request.onsuccess = function() {
                resolve(request.result);
            }
            request.onerror = function() {
                reject(request.target.errorCode);
            }
        });
    }
}